﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Extentions;
using Senparc.Weixin;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.QrCode;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using Senparc.Weixin.MP.Helpers;
using Senparc.Weixin.Open.OAuthAPIs;
using Senparc.Weixin.Open.QRConnect;
using Senparc.Weixin.TenPay.V3;
using Senparc.Weixin.WxOpen.AdvancedAPIs.WxApp.Business.JsonResult;
using TrainingReminderSystem.Model;
using Senparc.Weixin.Entities;

namespace TrainingReminderSystem.Bll
{
    /// <summary>
    /// 连接微信相关的帮助类
    /// </summary>
    public static class WechatHelper
    {
        #region 获取openID 和 设置/获取用户信息

        /// <summary>
        /// 获取openID
        /// 通过unionid能够关联到其他端的,比如微信公众号绑定成功了,小程序就无需绑定
        /// </summary>
        /// <param name="enumWxType"></param>
        /// <param name="code"></param>
        /// <param name="enumOpenIDType"></param>
        /// <param name="appid"></param>
        /// <returns>小程序里,返回值的Message就是session_key</returns>
        public static async Task<AjaxResult<WechatOAuthUserInfo>> GetOpenID(EnumWxType enumWxType, EnumOpenIDType enumOpenIDType, string code, string appid)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                return AjaxResult<WechatOAuthUserInfo>.ErrorResult("code不能为空");
            }

            var userInfoAr = WxOpenSdkHelper.GetOpenID(enumWxType, enumOpenIDType, code, appid);
            if (userInfoAr.Success == false) return userInfoAr;
            var userInfo = userInfoAr.Result;
            var enumRunProject = SysConfig.EnumRunProject;
            //新语法using
            using var db = CustomerLoginedBll.Db;
            //保存到数据库表
            if (enumRunProject == EnumRunProject.系统后台端)
            {
                var bll = new SysEmployeeOpenIDBll();
                SysEmployeeOpenID model = new SysEmployeeOpenID
                {
                    EnumOpenIDType = enumOpenIDType,
                    OpenID = userInfo.openid,
                    WxJson = !string.IsNullOrEmpty(userInfo.openid)
                        ? userInfo.ExToJson()
                        : string.Empty,
                    nickname = !string.IsNullOrEmpty(userInfo.nickname)
                        ? userInfo.nickname
                        : string.Empty,
                    headimgurl = !string.IsNullOrEmpty(userInfo.headimgurl)
                        ? userInfo.headimgurl
                        : string.Empty,
                    unionid = userInfo.unionid
                };
                if (!string.IsNullOrEmpty(model.unionid) && model.SysEmployeeID == null)
                {
                    model.SysEmployeeID = db.SysEmployeeOpenID
                        .Where(m => m.unionid == userInfo.unionid && m.EnumOpenIDType != enumOpenIDType && m.SysEmployeeID != null)
                        .Select(m => m.SysEmployeeID).FirstOrDefault();
                }
                var ar = await bll.Save(model, db);
                if (ar.Success == false)
                {
                    return AjaxResult<WechatOAuthUserInfo>.ErrorResult(ar.Message);
                }
            }
            else if (enumRunProject == EnumRunProject.微信客户端)
            {
                if (userInfo.WxDealerShop == null || string.IsNullOrEmpty(userInfo.WxDealerShop.SonPrimary))
                {
                    return AjaxResult<WechatOAuthUserInfo>.ErrorResult("返回值未设置店铺ID");
                }
                var bll = new SysCustomerOpenIDBll();
                var model = new SysCustomerOpenID
                {
                    SysCustomerID = null,
                    EnumOpenIDType = enumOpenIDType,
                    OpenID = userInfo.openid,
                    WxJson = !string.IsNullOrEmpty(userInfo.openid)
                    ? userInfo.ExToJson()
                    : string.Empty,
                    unionid = userInfo.unionid,
                    //查询一下
                    SysStoreID = userInfo.WxDealerShop.SonPrimary.ExToInt32(),

                    nickname = !string.IsNullOrEmpty(userInfo.nickname)
                        ? userInfo.nickname
                        : string.Empty,
                    headimgurl = !string.IsNullOrEmpty(userInfo.headimgurl)
                        ? userInfo.headimgurl
                        : string.Empty,
                };
                if (!string.IsNullOrEmpty(model.unionid) && model.SysCustomerID == null)
                {
                    model.SysCustomerID = db.SysCustomerOpenID
                        .Where(m => m.unionid == userInfo.unionid && m.EnumOpenIDType != enumOpenIDType &&
                                    m.SysCustomerID != null).Select(m => m.SysCustomerID).FirstOrDefault();
                }
                var ar = await bll.Save(model, db);
                if (ar.Success == false)
                {
                    return AjaxResult<WechatOAuthUserInfo>.ErrorResult(ar.Message);
                }
            }
            else
            {
                return AjaxResult<WechatOAuthUserInfo>.ErrorResult("参数错误");
            }
            return AjaxResult<WechatOAuthUserInfo>.SuccessResult(userInfo, userInfoAr.Message);
        }

        /// <summary>
        /// 小程序获取用户手机号
        /// </summary>
        /// <param name="enumWxType"></param>
        /// <param name="code"></param>
        /// <param name="appid"></param>
        /// <returns></returns>
        public static AjaxResult<GetUserPhoneNumberJsonResult> GetUserPhoneNumber(EnumWxType enumWxType, string code, string appid)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                return AjaxResult<GetUserPhoneNumberJsonResult>.ErrorResult("code不能为空");
            }
            AjaxResult<GetUserPhoneNumberJsonResult> result = WxOpenSdkHelper.GetUserPhoneNumber(enumWxType, code, appid);
            return result;
        }

        public static async Task<AjaxResult<WechatQRConnectUserInfo>> GetWebOpenID(string code, EnumWxType enumWxType = EnumWxType.管理后台)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                return AjaxResult<WechatQRConnectUserInfo>.ErrorResult("code不能为空");
            }

            AjaxResult<WechatQRConnectUserInfo> userInfoAr = WxOpenSdkHelper.GetWebOpenID(code, enumWxType);
            if (userInfoAr.Success == false) return userInfoAr;
            var userInfo = userInfoAr.Result;
            var enumRunProject = SysConfig.EnumRunProject;
            EnumOpenIDType enumOpenIDType = EnumOpenIDType.微信网站应用;
            //新语法using
            using var db = PcLoginedBll.Db;
            //保存到数据库表
            if (enumRunProject == EnumRunProject.系统后台端)
            {
                var bll = new SysEmployeeOpenIDBll();
                SysEmployeeOpenID model = new SysEmployeeOpenID
                {
                    EnumOpenIDType = enumOpenIDType,
                    OpenID = userInfo.openid,
                    WxJson = !string.IsNullOrEmpty(userInfo.openid)
                        ? userInfo.ExToJson()
                        : string.Empty,
                    nickname = !string.IsNullOrEmpty(userInfo.nickname)
                        ? userInfo.nickname
                        : string.Empty,
                    headimgurl = !string.IsNullOrEmpty(userInfo.headimgurl)
                        ? userInfo.headimgurl
                        : string.Empty,
                    unionid = userInfo.unionid
                };
                if (!string.IsNullOrEmpty(model.unionid) && model.SysEmployeeID == null)
                {
                    model.SysEmployeeID = db.SysEmployeeOpenID
                        .Where(m => m.unionid == userInfo.unionid && m.EnumOpenIDType != enumOpenIDType && m.SysEmployeeID != null)
                        .Select(m => m.SysEmployeeID).FirstOrDefault();
                }
                var ar = await bll.Save(model, db);
                if (ar.Success == false)
                {
                    return AjaxResult<WechatQRConnectUserInfo>.ErrorResult(ar.Message);
                }
            }
            else if (enumRunProject == EnumRunProject.微信客户端)
            {
                var bll = new SysCustomerOpenIDBll();
                int sysStoreID = userInfo.WxDealerShop.SonPrimary.ExToInt32();
                var model = new SysCustomerOpenID
                {
                    SysCustomerID = null,
                    EnumOpenIDType = enumOpenIDType,
                    OpenID = userInfo.openid,
                    WxJson = !string.IsNullOrEmpty(userInfo.openid)
                        ? userInfo.ExToJson()
                        : string.Empty,
                    unionid = userInfo.unionid,
                    //查询一下
                    SysStoreID = sysStoreID,
                    nickname = !string.IsNullOrEmpty(userInfo.nickname)
                        ? userInfo.nickname
                        : string.Empty,
                    headimgurl = !string.IsNullOrEmpty(userInfo.headimgurl)
                        ? userInfo.headimgurl
                        : string.Empty,
                };
                if (!string.IsNullOrEmpty(model.unionid) && model.SysCustomerID == null)
                {
                    model.SysCustomerID = db.SysCustomerOpenID
                        .Where(m => m.SysStoreID == sysStoreID && m.unionid == userInfo.unionid &&
                                    m.EnumOpenIDType != enumOpenIDType && m.SysCustomerID != null)
                        .Select(m => m.SysCustomerID).FirstOrDefault();
                }

                var ar = await bll.Save(model, db);
                if (ar.Success == false)
                {
                    return AjaxResult<WechatQRConnectUserInfo>.ErrorResult(ar.Message);
                }
            }
            else
            {
                return AjaxResult<WechatQRConnectUserInfo>.ErrorResult("参数错误");
            }
            return AjaxResult<WechatQRConnectUserInfo>.SuccessResult(userInfo, userInfoAr.Message);
        }

        /// <summary>
        /// 得到微信信息
        /// </summary>
        /// <returns></returns>
        public static AjaxResult<string> GetUserInfo()
        {
            var enumRunProject = SysConfig.EnumRunProject;
            if (enumRunProject == EnumRunProject.系统后台端)
            {
                var openID = PcLoginedBll.CurrentOpenID;
                return AjaxResult<string>.SuccessResult(openID.WxJson);
            }
            //if (enumRunProject == enumRunProject.微信客户端)
            //{
            //    var openID = ChezhuBaseBll.CurrentCustomerOpenID;
            //    return AjaxResult<string>.SuccessResult(openID.WxJson);
            //}

            return AjaxResult<string>.ErrorResult("参数错误");
        }

        /// <summary>
        /// 保存微信信息
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static async Task<AjaxResult<string>> SetUserInfo(string json)
        {
            var enumRunProject = SysConfig.EnumRunProject;
            if (enumRunProject == EnumRunProject.系统后台端)
            {
                var bll = new SysEmployeeOpenIDBll();
                var openID = PcLoginedBll.CurrentOpenID;
                openID.WxJson = json;
                await bll.Save(openID);
                return AjaxResult<string>.SuccessResult(string.Empty);
            }
            //if (enumRunProject == EnumRunProject.微信客户端)
            //{
            //    var bll = new CustomerOpenIDBll();
            //    var openID = ChezhuBaseBll.CurrentCustomerOpenID;
            //    openID.WxJson = json;
            //    bll.Save(openID);
            //    return AjaxResult<string>.SuccessResult(string.Empty);
            //}

            return AjaxResult<string>.ErrorResult("参数错误");
        }

        #endregion

        #region 微信支付

        /// <summary>
        /// 微信支付签名方式
        /// </summary>
        private const string WxPaySignType = "MD5";

        /// <summary>
        /// 得到JSAPI的参数
        /// </summary>
        /// <param name="enumOpenIDType"></param>
        /// <param name="enumWxType"></param>
        /// <param name="openID">trade_type=JSAPI时（即JSAPI支付），此参数必传</param>
        /// <param name="body">购买商品</param>
        /// <param name="outTradeNo">单号</param>
        /// <param name="money">金额是*100的分</param>
        /// <param name="returnUrl">成功回调页面路径</param>
        /// <param name="tenPayV3Type"></param>
        /// <param name="productID">32位 trade_type=NATIVE时，此参数必传。此参数为二维码中包含的商品ID，商户自行定义。</param>
        /// <returns></returns>
        public static AjaxResult<WxPayClass> GetWxPay(EnumWxType enumWxType, EnumOpenIDType enumOpenIDType, string body, string outTradeNo, int money, string returnUrl, string openID = StringExtentions.Empty, Senparc.Weixin.TenPay.TenPayV3Type tenPayV3Type = Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, string productID = StringExtentions.Empty)
        {
            try
            {
                //string appId, string mchId, string body, string outTradeNo, int totalFee, string spbillCreateIp, string notifyUrl, TenPayV3Type tradeType, string openid, string key, string nonceStr,
                string ip = ToolHelper.GetIpAddress();
                var post = new TenPayV3UnifiedorderRequestDataPost(enumWxType, enumOpenIDType, "", body, outTradeNo,
                    money, ip, returnUrl, tenPayV3Type, openID);
                post.ProductId = productID;
                var result = WxOpenSdkHelper.WxPay(post);
                if (result.Success == false)
                {
                    return result;
                }
                return result;
            }
            catch (Exception e)
            {
                ("微信支付下单异常:" + e.ExFullString()).ExLogError();
                return AjaxResult<WxPayClass>.ErrorResult("微信支付下单异常:" + e.ExMessageWithInner());
            }
        }

        /// <summary>
        /// 微信H5支付/小程序支付
        /// </summary>
        /// <param name="orderNumber"></param>
        /// <param name="enumWxType"></param>
        /// <param name="enumOpenIDType"></param>
        /// <returns></returns>
        public static AjaxResult<WxPayClass> WxPayAgain(EnumWxType enumWxType, EnumOpenIDType enumOpenIDType, string orderNumber)
        {
            try
            {
                return WxOpenSdkHelper.WxPayAgain(enumWxType, enumOpenIDType, orderNumber);
            }
            catch
            {
                return AjaxResult<WxPayClass>.ErrorResult("微信支付下单失败的,不能付款!");
            }
        }

        /// <summary>
        /// 查询是否成功
        /// </summary>
        /// <param name="enumWxType"></param>
        /// <param name="outTradeNo"></param>
        /// <param name="enumOpenIDType"></param>
        /// <returns></returns>
        public static AjaxResult<OrderQueryResult> WxPayQuery(EnumWxType enumWxType, EnumOpenIDType enumOpenIDType, string outTradeNo)
        {
            try
            {
                return WxOpenSdkHelper.WxPayQuery(enumWxType, enumOpenIDType, outTradeNo);
            }
            catch (Exception e)
            {
                ("微信支付查询订单异常:" + e.ExFullString()).ExLogError();
                return AjaxResult<OrderQueryResult>.ErrorResult("微信支付查询订单异常:" + e.ExMessageWithInner());
            }
        }

        #endregion

        #region 微信退款

        public static AjaxResult<RefundResult> WxRefunds(EnumWxType enumWxType, EnumOpenIDType enumOpenIDType, string out_trade_no, string transaction_id, string out_refund_no, int amountRefund, int amountTotal, string notify_url = null)
        {
            try
            {
                var post = new TenPayV3RefundRequestDataPost(enumWxType, enumOpenIDType, "", out_trade_no, transaction_id,
                    out_refund_no, amountTotal, amountRefund, notify_url);
                var result = WxOpenSdkHelper.WxRefunds(post);
                if (result.Success == false)
                {
                    return result;
                }
                return result;
            }
            catch (Exception e)
            {
                ("微信支付下单异常:" + e.ExFullString()).ExLogError();
                return AjaxResult<RefundResult>.ErrorResult("微信退款异常:" + e.ExMessageWithInner());
            }
        }

        public static AjaxResult<RefundQueryResult> WxRefundsQuery(EnumWxType enumWxType, EnumOpenIDType enumOpenIDType, string outRefundNo)
        {
            try
            {
                return WxOpenSdkHelper.WxRefundsQuery(enumWxType, enumOpenIDType, outRefundNo);
            }
            catch (Exception e)
            {
                ("微信支付查询订单异常:" + e.ExFullString()).ExLogError();
                return AjaxResult<RefundQueryResult>.ErrorResult("微信退款查询订单异常:" + e.ExMessageWithInner());
            }
        }

        #endregion

        #region 微信推送消息

        /// <summary>
        /// 推送单条
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        internal static void TemplateSend(SysWechatTemplate item)
        {
            if (item == null || string.IsNullOrEmpty(item.TemplateSendOpenIDs)) return;
            var openIDList = item.TemplateSendOpenIDs.Split('|');
            foreach (var openID in openIDList)
            {
                EnumWxType enumWxType = EnumWxType.客户端;//数字是一样的,完全能对应,不用写if
                if (item.EnumRunProject == EnumRunProject.系统后台端)
                {
                    enumWxType = EnumWxType.管理后台;
                }
                else if (item.EnumRunProject == EnumRunProject.微信客户端)
                {
                    enumWxType = EnumWxType.客户端;
                }
                try
                {
                    AjaxResult<SendTemplateMessageResult> ar =
                        WxOpenSdkHelper.SendTemplateMessage(enumWxType, openID, item.TemplateID,
                            item.Url, item.TemplateSendContent,
                            ExHttpContext.ServerHost + "api/Login/TemplateStatus", item.miniProgram, item.appid);
                    if (ar.Success == false)
                    {
                        item.EnumMsgState = EnumMsgState.推送失败;
                        item.Remark = ar.Message;
                        return;
                    }

                    SendTemplateMessageResult result = ar.Result;
                    if (result.errcode == ReturnCode.请求成功)
                    {
                        item.msgid = result.msgid.ToString();
                        item.EnumMsgState = EnumMsgState.推送中;
                    }
                    else
                    {
                        item.EnumMsgState = EnumMsgState.推送失败;
                        item.Remark = result.errcode + "|" + result.errmsg;
                    }
                }
                catch (Exception e)
                {
                    item.EnumMsgState = EnumMsgState.推送失败;
                    item.Remark = e.Message;

                    e.ExLogError($"推送消息(SysWechatTemplateID:{item.SysWechatTemplateID})报错");
                }
            }
        }

        internal static void TemplateSend2(SysWechatTemplate item)
        {
            if (item == null || string.IsNullOrEmpty(item.TemplateSendOpenIDs)) return;
            var openIDList = item.TemplateSendOpenIDs.Split('|');
            foreach (var openID in openIDList)
            {
                EnumWxType enumWxType = EnumWxType.客户端;//数字是一样的,完全能对应,不用写if
                if (item.EnumRunProject == EnumRunProject.系统后台端)
                {
                    enumWxType = EnumWxType.管理后台;
                }
                else if (item.EnumRunProject == EnumRunProject.微信客户端)
                {
                    enumWxType = EnumWxType.客户端;
                }
                try
                {
                    AjaxResult<WxJsonResult> ar =
                        WxOpenSdkHelper.SendTemplateMessage2(enumWxType, openID, item.TemplateID,
                            item.Url, item.TemplateSendContent, item.appid);
                    if (ar.Success == false)
                    {
                        item.EnumMsgState = EnumMsgState.推送失败;
                        item.Remark = ar.Message;
                        return;
                    }

                    var result = ar.Result;
                    if (result.errcode == ReturnCode.请求成功)
                    {
                        item.msgid = String.Empty;
                        item.EnumMsgState = EnumMsgState.推送中;
                    }
                    else
                    {
                        item.EnumMsgState = EnumMsgState.推送失败;
                        item.Remark = result.errcode + "|" + result.errmsg;
                    }
                }
                catch (Exception e)
                {
                    item.EnumMsgState = EnumMsgState.推送失败;
                    item.Remark = e.Message;

                    e.ExLogError($"推送小程序消息(SysWechatTemplateID:{item.SysWechatTemplateID})报错");
                }
            }
        }

        internal static void TemplateSendShort(SysWechatTemplate item)
        {
            if (item == null || string.IsNullOrEmpty(item.TemplateSendOpenIDs)) return;
            var openIDList = item.TemplateSendOpenIDs.Split('|');
            foreach (var openID in openIDList)
            {
                EnumWxType enumWxType = EnumWxType.客户端;//数字是一样的,完全能对应,不用写if
                if (item.EnumRunProject == EnumRunProject.系统后台端)
                {
                    enumWxType = EnumWxType.管理后台;
                }
                else if (item.EnumRunProject == EnumRunProject.微信客户端)
                {
                    enumWxType = EnumWxType.客户端;
                }
                try
                {
                    AjaxResult<SendTemplateMessageResult> ar =
                        WxOpenSdkHelper.SendTemplateMessageShort(enumWxType, openID, item.TemplateID,
                            item.Url, item.TemplateSendContent,
                            ExHttpContext.ServerHost + "api/Login/TemplateStatus", item.miniProgram, item.appid);
                    if (ar.Success == false)
                    {
                        item.EnumMsgState = EnumMsgState.推送失败;
                        item.Remark = ar.Message;
                        return;
                    }

                    SendTemplateMessageResult result = ar.Result;
                    if (result.errcode == ReturnCode.请求成功)
                    {
                        item.msgid = result.msgid.ToString();
                        item.EnumMsgState = EnumMsgState.推送中;
                    }
                    else
                    {
                        item.EnumMsgState = EnumMsgState.推送失败;
                        item.Remark = result.errcode + "|" + result.errmsg;
                    }
                }
                catch (Exception e)
                {
                    item.EnumMsgState = EnumMsgState.推送失败;
                    item.Remark = e.Message;

                    e.ExLogError($"推送消息(SysWechatTemplateID:{item.SysWechatTemplateID})报错");
                }
            }
        }

        /// <summary>
        /// 模版消息修改状态的回调
        /// </summary>
        /// <param name="msgID"></param>
        /// <param name="status"></param>
        public static void TemplateStatus(string msgID, string status)
        {
            if (string.IsNullOrEmpty(msgID) || string.IsNullOrEmpty(status)) return;
            Task.Run(() =>
            {
                EnumMsgState enumMsgState = EnumMsgState.推送中;
                enumMsgState = status == "success" ? EnumMsgState.推送成功 : EnumMsgState.推送失败;
                using (var db = PcLoginedBll.DbNoFilter)
                {
                    string sql =
                        $"update {nameof(SysWechatTemplate)} set {nameof(SysWechatTemplate.EnumMsgState)}={(int)enumMsgState},ReturnStatus='{status.ExClearSql()}' where {nameof(SysWechatTemplate.msgid)}='{msgID.ExClearSql()}';insert into {nameof(SysWechatTemplateRecord)}(SysWechatTemplateID, SysStoreID, SysEmployeeID, SysCustomerID, CreateDate, Remark) select SysWechatTemplateID,isnull(SysStoreID,0), SysEmployeeID, SysCustomerID,getDate(),'推送成功' from {nameof(SysWechatTemplate)} where {nameof(SysWechatTemplate.msgid)}='{msgID.ExClearSql()}'";
                    db.Database.ExExecuteSqlCommand(sql);
                }
            });
        }

        #endregion

        #region 微信客户的扫描二维码记录

        /// <summary>
        /// 获取微信客户二维码
        /// </summary>
        /// <returns></returns>
        public static async Task<AjaxResult<string>> CustomerQrCode()
        {
            using (Dal.DbEntities db = CustomerLoginedBll.Db)
            {
                var customer = SysCustomerBll.CurrentCustomer;
                var sr = db.SysShareRecord.OrderByDescending(m => m.SysShareRecordID).FirstOrDefault(m =>
                    m.SysCustomerID == customer.SysCustomerID && m.ExpireDate > DateTime.Now);
                if (sr != null)
                {
                    //return r.Result.ShareUrl;
                    var url = QrCodeApi.GetShowQrCodeUrl(sr.ShareTicket);
                    return AjaxResult<string>.SuccessResult(url);
                }

                var tran = db.Database.BeginTransaction();
                try
                {
                    var setting = SysSettingBll.GetModel(EnumSettingCode.分享类型, customer.GetParentID(), db);
                    sr = new SysShareRecord()
                    {
                        CreateDate = DateTime.Now,
                        SysCustomerID = customer.SysCustomerID,
                        EnumShareType = (EnumShareType)(setting.Value.ExToInt32()),
                        ExpireDate = null, //注释写错:qrResult.expire_seconds:该二维码有效时间，以秒为单位。 最大不超过2592000（即30天）。
                        ShareTicket = string.Empty,
                        ShareUrl = string.Empty,
                        Remark = null
                    };
                    var ajaxResult = await new SysShareRecordBll().Save(sr, db);
                    if (ajaxResult.Success == false)
                    {
                        return AjaxResult<string>.ErrorResult("保存分享记录出错:" + ajaxResult.Message);
                    }

                    int shareRecordID = ajaxResult.Result;
                    //int second = 2592000; //30天时间
                    //CreateQrCodeResult qrResult =
                    //    QrCodeApi.Create(AccessTokenContainer.GetAccessToken(appId), second, shareRecordID,
                    //        QrCode_ActionName.QR_STR_SCENE, shareRecordID.ToString());
                    string callbackUrl = ExHttpContext.ServerHost + "api/Login/Scan";
                    var currentOpenID = SysCustomerBll.CurrentOpenID;
                    AjaxResult<CreateQrCodeResult> arResult =
                        WxOpenSdkHelper.QrCode(EnumWxType.客户端, EnumOpenIDType.微信公众号,
                            currentOpenID.OpenID, shareRecordID.ToString(), callbackUrl,
                            EnumWxQrCodeType.临时二维码);
                    var qrResult = arResult.Result;
                    //string postData = "{\"expire_seconds\": 2592000, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"" + r.Result.ExtCustomerID + "\"}}}";
                    //注释写错:qrResult.expire_seconds:该二维码有效时间，以秒为单位。 最大不超过2592000（即30天）。
                    sr = db.SysShareRecord.FirstOrDefault(m => m.SysShareRecordID == shareRecordID);
                    sr.ExpireDate = DateTime.Now.AddSeconds(qrResult.expire_seconds);
                    sr.ShareTicket = qrResult.ticket;
                    sr.ShareUrl = qrResult.url;
                    db.SaveChanges();
                    tran.Commit();
                    tran = null;
                    var url = QrCodeApi.GetShowQrCodeUrl(qrResult.ticket);
                    return AjaxResult<string>.SuccessResult(url);
                }
                catch (Exception ex)
                {
                    ex.ExLogError();
                    return AjaxResult<string>.ErrorResult(ex.Message);
                }
                finally
                {
                    if (tran != null) tran.Rollback();
                }
            }
        }

        /// <summary>
        /// 微信客户的扫描二维码记录
        /// </summary>
        /// <param name="eventKey">分享记录</param>
        /// <param name="fromUserName"></param>
        public static void Scan(string eventKey, string fromUserName)
        {
            eventKey = eventKey.ExTrim();
            fromUserName = fromUserName.ExTrim();
            if (string.IsNullOrEmpty(fromUserName)) return;
            if (string.IsNullOrEmpty(eventKey)) return;
            int shareID = 0;
            if (int.TryParse(eventKey.Replace("qrscene_", string.Empty), out shareID) == false) return;
            System.Threading.Tasks.Task.Run(async () =>
            {
                //请求查看是否有 无则记录
                var bll = new SysQrCodeBll();
                SysQrCode qc = new SysQrCode()
                {
                    CompleteDate = null,
                    CreateDate = DateTime.Now,
                    IsComplete = false,
                    EventKey = eventKey,
                    OpenID = fromUserName,
                    SysShareRecordID = shareID,
                    SuccessObj = null,
                    Remark = null,
                    ID = 0,
                    SysShareRecord = null
                };
                await bll.Save(qc);
            });
        }

        #endregion
    }
}
